from flask import Blueprint, request, jsonify
from db import get_db
from datetime import datetime

meeting = Blueprint('meeting', __name__)

@meeting.route('/', methods=['POST'])
def add_meeting():
    data = request.json
    topic = data['topic']
    start_time = datetime.strptime(data['startTime'], '%Y-%m-%dT%H:%M')
    end_time = datetime.strptime(data['endTime'], '%Y-%m-%dT%H:%M')
    participants = data['participants']
    
    db = get_db()
    try:
        with db.cursor() as cursor:
            sql = """INSERT INTO MEETING (name, start_time, end_time) 
                     VALUES (%s, %s, %s)"""
            cursor.execute(sql, (topic, start_time, end_time))
            meeting_id = cursor.lastrowid
            
            if len(participants) >= 1:
                for participant_id in participants:
                    sql = "INSERT INTO ATTENDEE (mid, uid) VALUES (%s, %s)"
                    cursor.execute(sql, (meeting_id, participant_id))
                
        db.commit()
        return jsonify({
            "result": True,
            "message": "会议创建成功"
        })
        
    except Exception as e:
        db.rollback()
        return jsonify({
            "result": False,
            "message": f"创建会议失败：{str(f'{e}')}"
        })
    finally:
        db.close()

@meeting.route('/', methods=['GET'])
def get_all_meetings():
    db = get_db()
    try:
        with db.cursor() as cursor:
            sql = """
                SELECT m.mid, m.name as topic, m.start_time, m.end_time
                FROM MEETING m
                ORDER BY m.start_time DESC
            """
            cursor.execute(sql)
            meetings = cursor.fetchall()
            
            for meeting in meetings:
                sql = """
                    SELECT u.uid, u.uname, a.state as check_in_status
                    FROM USER u
                    JOIN ATTENDEE a ON u.uid = a.uid
                    WHERE a.mid = %s
                """
                cursor.execute(sql, (meeting['mid'],))
                participants = cursor.fetchall()
                meeting['participants'] = participants
                
            return jsonify({
                "result": True,
                "meetings": meetings
            })
            
    except Exception as e:
        return jsonify({
            "result": False,
            "message": f"获取会议信息失败：{str(e)}"
        })
    finally:
        db.close()

@meeting.route('/<int:uid>', methods=['GET'])
def get_user_meetings(uid):
    db = get_db()
    try:
        with db.cursor() as cursor:
            sql = """
                SELECT m.mid, m.name as topic, m.start_time, m.end_time, a.state as check_in_status
                FROM MEETING m
                JOIN ATTENDEE a ON m.mid = a.mid
                WHERE a.uid = %s
                ORDER BY m.start_time DESC
            """
            cursor.execute(sql, (uid,))
            meetings = cursor.fetchall()
            return jsonify({
                "result": True,
                "meetings": meetings
            })
    except Exception as e:
        return jsonify({
            "result": False,
            "message": f"获取会议信息失败：{str(e)}"
        })
    finally:
        db.close()

@meeting.route('/checkin', methods=['POST'])
def check_in():
    data = request.json
    meeting_id = data['meetingId']
    user_id = data['userId']
    face_result = data['faceResult']
    
    if face_result['error_code'] != 0:
        return jsonify({
            "result": False,
            "message": "人脸识别失败",
            "info": f'{face_result}'
        })
    
    if str(face_result['result']['user_list'][0]['user_id']) != str(user_id):
        return jsonify({
            "result": False,
            "message": "人脸验证失败，请重试",
            "info": f'{face_result}'
        })
    
    db = get_db()
    try:
        with db.cursor() as cursor:
            sql = "UPDATE ATTENDEE SET state = 1 WHERE mid = %s AND uid = %s"
            cursor.execute(sql, (meeting_id, user_id))
        db.commit()
        return jsonify({
            "result": True,
            "message": "签到成功"
        })
    except Exception as e:
        db.rollback()
        return jsonify({
            "result": False,
            "message": f"签到失败：{str(e)}"
        })
    finally:
        db.close()